package com.zhuhjay.validation;

import cn.hutool.core.util.StrUtil;
import com.zhuhjay.annotation.Matching;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 两个泛型参数，第一个为注解名称，第二个为实际字段的数据类型
 * @author ZhuHJay
 * @date 2023/1/11 21:15
 */
public class MatchingValidator implements ConstraintValidator<Matching, String> {

    private Pattern pattern;
    private String message;

    @Override
    public void initialize(Matching matching) {
        String regular = matching.value().getRegular();
        pattern = Pattern.compile(regular);
        message = matching.value().getMessage();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isNotBlank(value)) {
            if (pattern.matcher(value).matches()) {
                return true;
            }
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return false;
    }
}
